#include "FileStream.h"

namespace IO
{
	bool IO::B_StreamIN(const std::string& Filename)
	{
		Stream.open(Filename, std::ios::in | std::ios::binary);
		if(!Stream.is_open())
			return false;
		Stream.seekg(0, std::ios::end);
		size = Stream.tellg();
		Stream.seekg(0, std::ios::beg);
		position = 0;
		return true;
	}

	bool IO::B_StreamOUT(const std::string& Filename)
	{
		Stream.open(Filename, std::ios::out | std::ios::binary);
		if(!Stream.is_open())
			return false;
		Stream.seekg(0, std::ios::beg);
		position = 0;
		return true;
	}

	bool IO::N_StreamOUT(const std::string& Filename)
	{
		Stream.open(Filename, std::ios::out);
		if(!Stream.is_open())
			return false;
		Stream.seekg(0, std::ios::beg);
		return true;
	}

	void IO::WriteString(std::string text)
	{
		Stream.write(const_cast<char*>(text.c_str()), text.length() + 1);
	}

	void IO::WriteString(std::string& time, std::string text)
	{
		Stream << time << "::> \t" << text;
	}

	void IO::Write(int& ret)
	{
		Stream << "0x"<< std::hex << ret << " ";
	}

	uint32 IO::SearchChunk(const std::string& ChunkName)
	{
		uint32 point = 0;
		uint32 Start = 0;
		uint32 End = size;
		std::string CNK;
		int i;
		char chunk;
		for( ; Start != End; Start + 4)
		{
			i = 0;
			position = point;
			Stream.seekg(position, std::ios::beg);
			do
			{
				Stream.read(reinterpret_cast<char*>(&chunk), sizeof(char));
				CNK.push_back(chunk);
				i++;
			}while(i < 4);
			point += 4;
			if(CNK == ChunkName)
			{
				point -= 4;
				break;
			}
			CNK.clear();
		}
		if(Start == End)
			throw std::exception("Could not find Chunk");
		return point;
	}
}